package cn.zhiquxing.test;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Consumer implements Runnable{
    
    public static final int consume_gap = 100;
    
    static final AtomicInteger turn = new AtomicInteger(0);
    
    static final AtomicInteger consumer_no = new AtomicInteger(1);

    /**
     * 消费者名称
     */
    private String name;
    
    Callable action;
    
    int gap = consume_gap;

    public Consumer(Callable action, int gap) {
        this.action = action;
        this.gap = gap;
        this.name = "consumer_" + consumer_no.getAndIncrement();
    }

    @Override
    public void run() {
        while (true) {
            turn.getAndIncrement();
            try {
                Object call = action.call();
                if (call != null) {
                    System.out.println("第" + turn.get() + "次消费" + call);
                }
                TimeUnit.MILLISECONDS.sleep(gap);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
